package com.example.sunmiv1.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.VipDetailsAdapter;
import com.example.sunmiv1.adapter.VipRechargeAdapter;
import com.example.sunmiv1.entity.GuideBean;
import com.example.sunmiv1.entity.MemberInfoBean;
import com.example.sunmiv1.entity.VipTransactionBean;
import com.example.sunmiv1.utils.ByteArrayTohexHepler;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.utils.ByteArrayTohexHepler.ByteArrayToHexString;
import static com.example.sunmiv1.utils.ByteArrayTohexHepler.flipHexStr;

public class VipDetailsActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.vipDetails_money)
    TextView vipDetailsMoney;
    @BindView(R.id.vipDetails_integral)
    TextView vipDetailsIntegral;
    @BindView(R.id.vipDetails_allRechargeMoney)
    TextView vipDetailsAllRechargeMoney;
    @BindView(R.id.vipDetails_listView)
    ListView vipDetailsListView;
    @BindView(R.id.vipDetails_nfcCard)
    TextView vipDetailsNfcCard;
    @BindView(R.id.vipDetails_bind)
    TextView vipDetailsBind;
    @BindView(R.id.iv_bind_off)
    ImageView ivBindOff;
    @BindView(R.id.et_bind_bind)
    EditText etBindBind;
    @BindView(R.id.tv_bind_cancel)
    TextView tvBindCancel;
    @BindView(R.id.tv_bind_confirm)
    TextView tvBindConfirm;
    @BindView(R.id.linear_bind)
    LinearLayout linearBind;
    @BindView(R.id.iv_unbind_off)
    ImageView ivUnbindOff;
    @BindView(R.id.et_unbind_bind)
    EditText etUnbindBind;
    @BindView(R.id.tv_unbind_cancel)
    TextView tvUnbindCancel;
    @BindView(R.id.tv_unbind_confirm)
    TextView tvUnbindConfirm;
    @BindView(R.id.linear_unbind)
    LinearLayout linearUnbind;
    @BindView(R.id.spinner_bind_bind)
    Spinner spinnerBindBind;
    @BindView(R.id.vipDetails_recharge)
    TextView vipDetailsRecharge;
    @BindView(R.id.vipDetails_update)
    TextView vipDetailsUpdate;
    @BindView(R.id.vipDetails_call)
    TextView vipDetailsCall;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private List<VipTransactionBean.PaylistBean> list;//交易記錄的集合
    private List<MemberInfoBean.RechargeBean> rechargeList;//充值優惠集合
    private Intent intent;
    private int coupon_index = 9999;//選擇的第幾個優惠
    private VipRechargeAdapter vipRechargeAdapter;
    private MemberInfoBean memberinfoBean;//會員詳細信息的實體類
    private VipTransactionBean vipTransactionBean;//交易記錄的實體類
    private VipDetailsAdapter vipDetailsAdapter;
    private int user_type = 1;//1，收銀員；2，店長
    private static final String TAG = "VipDetailsActivity";


    private GuideBean guideBean;
    private int guide_index;
    private List<String> guideNameList = new ArrayList<>();
    private List<GuideBean.GuideListBean> guideList = new ArrayList<>();

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
//                    Toast.makeText(context, memberinfoBean.getMsg(), Toast.LENGTH_SHORT).show();
                    vipDetailsIntegral.setText(memberinfoBean.getVip().getIntegral());
                    vipDetailsMoney.setText(memberinfoBean.getVip().getBalance());
                    if (memberinfoBean.getVip().getCard_key() == null || TextUtils.isEmpty(memberinfoBean.getVip().getCard_key())
                            || "0".equals(memberinfoBean.getVip().getCard_key())) {
                        vipDetailsNfcCard.setText(R.string.vipDetail1);
                        vipDetailsBind.setText(R.string.vipDetail2);
                    } else {
                        vipDetailsNfcCard.setText(memberinfoBean.getVip().getCard_key());
                        vipDetailsBind.setText(R.string.vipDetail3);
                    }
                    vipDetailsAllRechargeMoney.setText(getString(R.string.vipDetail4) + memberinfoBean.getVip().getSummoney() + getString(R.string.vipDetail5));
                    if (memberinfoBean.getRecharge() != null && memberinfoBean.getRecharge().size() > 0) {
                        for (MemberInfoBean.RechargeBean rechargeBean : memberinfoBean.getRecharge()) {
                            rechargeList.add(rechargeBean);
                        }

                    }
                    break;
                case 2:
                    loadingDialog.dismiss();
//                    Toast.makeText(context, memberinfoBean.getMsg(), Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    loadingDialog.dismiss();
//                    Toast.makeText(context, vipTransactionBean.getMsg(), Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < vipTransactionBean.getPaylist().size(); i++) {
                        list.add(vipTransactionBean.getPaylist().get(i));
                    }
                    setVipDetailsAdapter();
                    break;
                case 4:
                    loadingDialog.dismiss();
//                    Toast.makeText(context, vipTransactionBean.getMsg(), Toast.LENGTH_SHORT).show();
                    setVipDetailsAdapter();
                    break;
                case 5:
                    guideList.clear();
                    guideNameList.clear();
                    GuideBean.GuideListBean dataBean = new GuideBean.GuideListBean();
                    dataBean.setId("0");
                    dataBean.setGuidename("無");
                    guideList.add(dataBean);
                    guideNameList.add("無");
                    for (int i = 0; i < guideBean.getGuide_list().size(); i++) {
                        guideList.add(guideBean.getGuide_list().get(i));
                        guideNameList.add(guideBean.getGuide_list().get(i).getGuidename());
                    }
                    setCateAdapter();
                    break;
                case 6:
                    guideList.clear();
                    guideNameList.clear();
                    GuideBean.GuideListBean dataBean1 = new GuideBean.GuideListBean();
                    dataBean1.setId("0");
                    dataBean1.setGuidename("無");
                    guideList.add(dataBean1);
                    guideNameList.add("無");
                    setCateAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_vip_details);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        if ("3".equals(aCache.getAsString("userType"))) {
            vipDetailsRecharge.setVisibility(View.VISIBLE);
        } else {
            vipDetailsRecharge.setVisibility(View.INVISIBLE);
        }
        titleTitle.setText(R.string.vipDetail6);
        initData();
        //nfc
        PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
        if (mNfcAdapter != null && !isOpenNfc) {
            Toast.makeText(context, "如需使用nfc功能，請到設置中開啓！", Toast.LENGTH_SHORT).show();
        }
    }

    private void setCateAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, guideNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop);
        spinnerBindBind.setAdapter(arrayAdapter);
    }

    private void initData() {
        list = new ArrayList<>();
        rechargeList = new ArrayList<>();
        getGuide();
        spinnerBindBind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                guide_index = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void setVipDetailsAdapter() {
        if (vipDetailsAdapter == null) {
            vipDetailsAdapter = new VipDetailsAdapter(context, list);
            vipDetailsListView.setAdapter(vipDetailsAdapter);
        } else {
            vipDetailsAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getVipInfo();
        list.clear();
        getRechargeList();
        if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Toast.makeText(context, "onNewIntent", Toast.LENGTH_SHORT).show();

        String ex_id;
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String num1 = ByteArrayToHexString(tagFromIntent.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        ex_id = num;
        Log.e("==================", ex_id);
        //Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
        etBindBind.setText(ex_id);
        etBindBind.setSelection(ex_id.length());
    }

    @OnClick({R.id.title_back,
            /**綁定實體卡*/
            R.id.vipDetails_bind, R.id.iv_bind_off, R.id.tv_bind_cancel, R.id.tv_bind_confirm, R.id.linear_bind,
            /**解綁會員卡*/
            R.id.iv_unbind_off, R.id.tv_unbind_cancel, R.id.tv_unbind_confirm, R.id.linear_unbind,
            R.id.vipDetails_recharge, R.id.vipDetails_update, R.id.vipDetails_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.vipDetails_recharge:
                intent = new Intent(context, VipRechargeActivity.class);
                intent.putExtra("vid", memberinfoBean.getVip().getId());
                startActivity(intent);
                break;
            case R.id.vipDetails_update:
                intent = new Intent(context, UpdateInfoActivity.class);
                intent.putExtra("vid", memberinfoBean.getVip().getId());
                startActivity(intent);
                break;
            case R.id.vipDetails_call:
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                //    設置Title的內容
                //    設置Content來顯示一個信息
                builder.setMessage("是否撥打" + memberinfoBean.getVip().getMobile_phone() + "這個電話");

                builder.setNegativeButton("取消", (dialog, which) -> {

                });
                //    設置一個PositiveButton
                builder.setPositiveButton("確定", (dialog, which) -> Dialing());
                builder.show();
                break;
            case R.id.title_back:
                finish();
                break;

            case R.id.vipDetails_bind:
                if (memberinfoBean.getVip().getCard_key() == null || TextUtils.isEmpty(memberinfoBean.getVip().getCard_key())
                        || "0".equals(memberinfoBean.getVip().getCard_key())) {
                    linearBind.setVisibility(View.VISIBLE);
                } else {
                    linearUnbind.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_bind_off:
                etBindBind.setText("");
                linearBind.setVisibility(View.GONE);
                break;
            case R.id.tv_bind_cancel:
                etBindBind.setText("");
                linearBind.setVisibility(View.GONE);
                break;
            case R.id.tv_bind_confirm:
                if (TextUtils.isEmpty(etBindBind.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入正確會員卡編號綁定", Toast.LENGTH_SHORT).show();
                } else {
                    bind();
                }
                break;
            case R.id.linear_bind:
                break;
            case R.id.iv_unbind_off:
                etUnbindBind.setText("");
                linearUnbind.setVisibility(View.GONE);
                break;
            case R.id.tv_unbind_cancel:
                etUnbindBind.setText("");
                linearUnbind.setVisibility(View.GONE);
                break;
            case R.id.tv_unbind_confirm:
                if (TextUtils.isEmpty(etUnbindBind.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入會員密碼", Toast.LENGTH_SHORT).show();
                } else {
                    unbind();
                }
                break;
            case R.id.linear_unbind:
                break;
        }
    }

    private void getGuide() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_GUIDE, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                guideBean = GsonUtils.JsonToBean(text, GuideBean.class);
                Message msg = new Message();
                if (guideBean.getStatus() == 1) {
                    msg.what = 5;
                } else {
                    msg.what = 6;
                }
                handler.sendMessage(msg);
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    private void bind() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", memberinfoBean.getVip().getId());//會員id
            jsonObject.put("cardnum", memberinfoBean.getVip().getMobile_phone());//會員卡號
            jsonObject.put("card_key", etBindBind.getText().toString());//實體卡id
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));//商戶id
            if (guide_index != 9999) {
                jsonObject.put("guideid", guideList.get(guide_index).getId());
            } else {
                jsonObject.put("guideid", 0);
            }
            HttpUtils.post(context, Common.VIP_BIND, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            etBindBind.setText("");
                            spinnerBindBind.setSelection(0);
                            linearBind.setVisibility(View.GONE);
                            getVipInfo();
                        }
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void unbind() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", memberinfoBean.getVip().getId());//會員id
            jsonObject.put("pwd", etUnbindBind.getText().toString());//會員支付密碼
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));//商戶id
            HttpUtils.post(context, Common.VIP_UNBIND, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        loadingDialog.dismiss();
                        if (json.getInt("status") == 1) {
                            etUnbindBind.setText("");
                            linearUnbind.setVisibility(View.GONE);
                            getVipInfo();
                        }
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void getVipInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vid", getIntent().getStringExtra("vid"));
            jsonObject.put("storeTag", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(context, Common.GET_MEMBER_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    memberinfoBean = GsonUtils.JsonToBean(text, MemberInfoBean.class);
                    Message msg = new Message();
                    if (memberinfoBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getRechargeList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vid", getIntent().getStringExtra("vid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(context, Common.GET_VIP_RECORD, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    vipTransactionBean = GsonUtils.JsonToBean(text, VipTransactionBean.class);
                    Message msg = new Message();
                    if (vipTransactionBean.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void Dialing() {
        if (ContextCompat.checkSelfPermission(VipDetailsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(VipDetailsActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 100);
            return;
        }
        intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + memberinfoBean.getVip().getMobile_phone()));
        intent.setAction("android.intent.action.CALL");
        startActivity(intent);
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
//                    Bundle bundle = data.getExtras();
//                    vipDetailsRechargeCode.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
//                    getGoodname(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    Dialing();
                } else {
                    // 被禁止授權
                    Toast.makeText(this, "請至權限中心打開本應用的撥打電話權限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


}
